﻿using System.Drawing;
using System.Windows.Forms;

namespace Useful.GUI.HierarchyDataGridView
{
    public class DataGridViewColumnCheckedHeaderCell : DataGridViewColumnHeaderCell
    {
        private bool isChecked;
        private Rectangle cbRect = new Rectangle(20, 0, 20, 20);

        protected override void Paint(Graphics graphics, Rectangle clipBounds, Rectangle cellBounds, int rowIndex, DataGridViewElementStates dataGridViewElementState, object value, object formattedValue, string errorText, DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts)
        {
            if (isChecked)
                cellStyle.BackColor = Color.LightBlue;

            base.Paint(graphics, clipBounds, cellBounds, rowIndex, dataGridViewElementState, value, formattedValue, errorText, cellStyle, advancedBorderStyle, paintParts);

            //cbRect.X = cellBounds.Width - cbRect.Width;

            Rectangle rect = new Rectangle(new Point(cellBounds.X + cbRect.X, cellBounds.Y + cbRect.Y), cbRect.Size);

            ControlPaint.DrawCheckBox(graphics, rect, isChecked ? ButtonState.Checked : ButtonState.Normal);
        }

        protected override void OnMouseClick(DataGridViewCellMouseEventArgs e)
        {
            if (cbRect.Contains(e.Location))
            {
                isChecked = !isChecked;
            }
            else
                base.OnMouseClick(e);
        }

        public bool IsMouseInCell(Point p)
        {
            Rectangle rect1 = DataGridView.GetCellDisplayRectangle(ColumnIndex, RowIndex, false);
            Rectangle rect2 = new Rectangle(new Point(rect1.X + cbRect.X, rect1.Y + cbRect.Y), cbRect.Size);

            return !rect2.Contains(p);
        }

        public void ProcessCheck()
        {
            isChecked = !isChecked;
        }
    }
}
